package com.aaa.forum.services.impl;

import com.aaa.forum.common.AppResult;
import com.aaa.forum.common.ResultCode;
import com.aaa.forum.dao.ArticleMapper;
import com.aaa.forum.exception.ApplicationException;
import com.aaa.forum.model.Article;
import com.aaa.forum.model.Board;
import com.aaa.forum.model.User;
import com.aaa.forum.services.IArticleService;
import com.aaa.forum.services.IBoardService;
import com.aaa.forum.services.IHistoryService;
import com.aaa.forum.services.IUserService;
import com.aaa.forum.uitls.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    // 注入 userService 和 boardService
    // 注意不要循环引用, 虽然Spring可以处理循环引用, 但是尽量不要写这样的代码
    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;

    @Resource
    private IHistoryService historyService;

    @Override
    public void create(Article article) {
        // 参数校验
        if (article == null || article.getUserId() == null || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle()) || StringUtil.isEmpty(article.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 设置默认值
        article.setVisitCount(0);           // 访问数量
        article.setLikeCount(0);            // 点赞数量
        article.setReplyCount(0);           // 回复数量
        article.setMarkCount(0);            // 收藏数量
        article.setState((byte) 1);         // 待审核状态
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);        // 创建日期
        article.setUpdateTime(date);        // 更新日期
        // 写入数据库
        int row = articleMapper.insertSelective(article);
        if (row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("发帖成功, userId = " + article.getUserId()
                + ", boardId = " + article.getBoardId()
                + ", articleId = " + article.getId());

        // 文章id是数据库自动生成的主键，在mapper中设置了，插入成功后，会拿到这个自动生成的id
    }

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 非空校验
        if (boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验板块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 调用dao, 查询并返回结果
        return articleMapper.selectAllByBoardId(boardId);
    }

    @Override
    public Article selectDetailById(Long userId, Long articleId) {
        // 非空校验
        if (userId == null || userId <= 0 || articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用dao, 查询帖子详情
        Article article = articleMapper.selectDetailById(articleId);
        // 校验是否为空
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 更新帖子访问数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        // 校验是否更新成功
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        // 更新历史记录表
        historyService.update(userId, articleId);
        // 更新返回结果的访问数量
        article.setVisitCount(updateArticle.getVisitCount());
        return article;
    }

    @Override
    public void modify(Long id, String title, String content, Long boardId) {
        // 非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询帖子，校验是否为空
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 构造要更新的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setBoardId(boardId);
        updateArticle.setUpdateTime(new Date());
        updateArticle.setState((byte) 1);
        // 调用dao, 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        if (article.getState() == 0) {
            // 更新用户发帖数量
            User existsUser = userService.selectById(article.getUserId());
            if (existsUser != null && existsUser.getDeleteState() == 0) {
                // 用户未被删除
                userService.subOneArticleCountById(article.getUserId());
            }
            // 更新板块帖子数量
            Board existsBoard = boardService.selectById(article.getBoardId());
            if (existsBoard != null && existsBoard.getDeleteState() == 0) {
                // 板块未被删除
                boardService.subOneArticleCountById(article.getBoardId());
            }
        }
    }

    @Override
    public Article selectById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void deleteById(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2. 查询id对应的帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS + ", articleId = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 3. 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
        // 4. 更新deleteState字段
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        if (article.getState() == 0) {
            // 更新用户发帖数量
            User existsUser = userService.selectById(article.getUserId());
            if (existsUser != null && existsUser.getDeleteState() == 0) {
                // 用户未被删除
                userService.subOneArticleCountById(article.getUserId());
            }
            // 更新板块帖子数量
            Board existsBoard = boardService.selectById(article.getBoardId());
            if (existsBoard != null && existsBoard.getDeleteState() == 0) {
                // 板块未被删除
                boardService.subOneArticleCountById(article.getBoardId());
            }
        }
        // 删除历史记录
        historyService.deleteByArticleId(id);
        log.info("删除帖子成功, userId = " + article.getUserId()
                + ", boardId = " + article.getBoardId()
                + ", articleId = " + article.getId());

    }

    @Override
    public void addOneReplyCountById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            // 帖子不存在 或 已删除
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            // 帖子封贴状态
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        // 调用 dao, 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void addOneLikeCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            // 帖子不存在 或 已删除
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        // 调用 dao, 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void subOneLikeCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            // 帖子不存在 或 已删除
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() - 1);
        if (updateArticle.getLikeCount() < 0) updateArticle.setLikeCount(0);
        // 调用 dao, 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void addOneMarkCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            // 帖子不存在 或 已删除
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setMarkCount(article.getMarkCount() + 1);
        // 更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void subOneMarkCountById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            // 帖子不存在 或 已删除
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setMarkCount(article.getMarkCount() - 1);
        if (updateArticle.getMarkCount() < 0) updateArticle.setMarkCount(0);
        // 更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectAllByUserId(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectAllByUserId(userId);
    }

    @Override
    public List<Article> selectBySubscribe(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectBySubscribe(userId);
    }

    @Override
    public List<Article> selectByDefaultCollection(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByDefaultCollection(userId);
    }

    @Override
    public List<Article> selectByCollectionId(Long collectionId) {
        if (collectionId == null || collectionId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByCollectionId(collectionId);
    }

    @Override
    public List<Article> selectByTitle(String title) {
        if (StringUtil.isEmpty(title)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByTitle(title);
    }

    @Override
    public List<Article> selectAllExamine() {
        return articleMapper.selectAllExamine();
    }

    @Override
    public List<Article> selectAllExamineByUserId(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectAllExamineByUserId(userId);
    }

    @Override
    public Article selectAllState(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectAllState(id);
    }

    @Override
    public void modifyState(Long id, Byte state) {
        // 参数校验
        if (id == null || id <= 0 || (state != 0 && state != 2)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验帖子是否存在
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setState(state);
        updateArticle.setUpdateTime(new Date());
        // 调用dao, 更新帖子状态
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        if (state == 0 && article.getState() != 0) {
            // 更新用户发帖数量
            User existsUser = userService.selectById(article.getUserId());
            if (existsUser != null && existsUser.getDeleteState() == 0) {
                // 用户未被删除
                userService.addOneArticleCountById(article.getUserId());
            }
            // 更新板块帖子数量
            Board existsBoard = boardService.selectById(article.getBoardId());
            if (existsBoard != null && existsBoard.getDeleteState() == 0) {
                // 板块未被删除
                boardService.addOneArticleCountById(article.getBoardId());
            }
        }
    }
}
